package com.cby.code.util;

import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;


public class ProcessUtils {

  /**
   * 获取当前的pid
   * @return
   */
  public static int getMyPid() {
    return android.os.Process.myPid();
  }

  /**
   * 是否为主进程
   * @param context
   * @return
   */
  public static boolean isMainProcess(Context context) {
    String processName = getCurrentProcessName(context);
    if (processName.equals(context.getPackageName())) {
      return true;
    }
    return false;
  }

  /**
   * 获取当前进程名称
   * @param context
   * @return
   */
  public static String getCurrentProcessName(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (activityManager == null) {
      return null;
    }

    List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();

    if (processes != null) {
      int pid = android.os.Process.myPid();
      for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
        if (processInfo.pid == pid && !TextUtils.isEmpty(processInfo.processName)) {
          return processInfo.processName;
        }
      }
    }

    return getCurrentProcessName();
  }

  /**
   * 返回当前的进程名
   *
   * @return
   */
  private static String getCurrentProcessName() {
    FileInputStream in = null;
    try {
      String fn = "/proc/self/cmdline";
      in = new FileInputStream(fn);
      byte[] buffer = new byte[256];
      int len = 0;
      int b;
      while ((b = in.read()) > 0 && len < buffer.length) {
        buffer[len++] = (byte) b;
      }
      if (len > 0) {
        String s = new String(buffer, 0, len, "UTF-8");
        return s;
      }
    } catch (Throwable e) {

    } finally {
      if(in != null ){
        try {
          in.close();
        } catch (IOException e) {
        }
      }
    }
    return null;
  }
}
